import { InjectableComponent } from "../../inject";
import { ViewParams } from "../ViewDefine";

export default class UIDelegateComp extends InjectableComponent {

    static FUNC_ADDED: string = 'triggerAdded';
    static FUNC_REMOVE_BEFORE: string = 'triggerBeforeRemove';
    static FUNC_REMOVED: string = 'triggerRemoved';


    viewParams: ViewParams | null = null;

    onLoad() {
        super.onLoad();

    }

    onDestroy() {
        let vp = this.viewParams!;

        // 触发所有组件上的onRemoved
        this.triggerEvents(UIDelegateComp.FUNC_REMOVED, vp);

        if (vp.callbacks && typeof vp.callbacks!.onRemoved === 'function') {
            vp.callbacks!.onRemoved(this.node, vp.payload);
        }

        this.viewParams = null;

        super.onDestroy();
    }

    add() {
        let vp = this.viewParams!;

        if (vp.callbacks && typeof vp.callbacks!.onAdded === 'function') {
            vp.callbacks!.onAdded(this.viewParams.uuid, this.node, vp.payload);
        }

        // 触发所有组件上的onAdded
        this.triggerEvents(UIDelegateComp.FUNC_ADDED, vp);
    }

    remove(isDestroy: boolean) {
        let vp = this.viewParams!;

        if (vp.valid) {
            // 触发所有组件上的onBeforeRemove
            this.triggerEvents(UIDelegateComp.FUNC_REMOVE_BEFORE, vp);

            if (vp.callbacks && typeof vp.callbacks!.onBeforeRemove === 'function') {
                // onBeforeRemove(node: Node, removeCallback: Function)
                // 如果callbacks 有onBeforeRemvoe,参数removeCallback必须要调用
                vp.callbacks!.onBeforeRemove(this.node, () => {
                    this.removed(vp, isDestroy);
                });
            } else {
                this.removed(vp, isDestroy);
            }
        }
    }

    private removed(vp: ViewParams, isDestroy: boolean) {
        if (isDestroy) {
            this.node.destroy();
        } else {
            this.node.removeFromParent();
        }
    }

    protected triggerEvents(event: string, vp: ViewParams) {
        for (let i = 0; i < this.node.components.length; i++) {
            let component: any = this.node.components[i];
            let func = component[event];
            if (func) {
                func.call(component, vp);
            }
        }
    }
}